import Util from '../Util.js';
import Msg from './Message.js';

const dateMap = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '廿十', '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '卅十'];
const monthMap = ['正月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '冬月', '腊月', ]

function builtCalendar(calendarDays) {
    const container = document.createElement('ul');
    let HTMLString = '';

    for (let i = 0; i < 42; i++) {
        HTMLString += `
            <li>
                <span class="cyear"></span>
                <span class="nyear"></span>
            </li>`;
    }

    container.innerHTML = HTMLString;
    calendarDays.appendChild(container);
}

export default class Time {
    constructor(date) {
        this.date = date;
    }

    setTime(idSelector, date, full) {
        const time = document.querySelector(idSelector);

        const timer = Util.timer();

        if (time) {
            timer.set(() => {
                date.setSeconds(date.getSeconds() + 1);
                if (full) {
                    time.innerHTML = `${Util.addZero(date.getHours(), 2)}:${Util.addZero(date.getMinutes(), 2)}:${Util.addZero(date.getSeconds(), 2)}`
                } else {
                    time.innerHTML = `${Util.addZero(date.getHours(), 2)}:${Util.addZero(date.getMinutes(), 2)}`;
                }
            }, 1000);
        } else {
            new Msg({ icon: './images/windows.png' }, '时间设置错误');
        }
    }

    setDate(idSelector) {
        const elem = document.querySelector(idSelector);

        const lunarDate = this.getLunarDate();

        if (elem) {
            elem.innerHTML = `${this.date.getFullYear()}年${this.date.getMonth() + 1}月${this.date.getDate()}日 ${lunarDate[0]} ${monthMap[lunarDate[1] - 1]}${dateMap[lunarDate[2] - 1]}`;
        } else {
            Util.globalMessage('日期设置错误', 'error');
        }
    }

    setMonth(idSelector) {
        const elem = document.querySelector(idSelector);

        if (elem) {
            elem.innerHTML = `${this.date.getFullYear()}年${this.date.getMonth() + 1}月`;
        } else {
            Util.globalMessage('日期设置错误', 'error');
        }
    }

    getLunarDate() {
        const dataStr = this.date.toLocaleString('ja-JP-u-ca-chinese');
        const year = dataStr.substring(0, 3);
        const dateArr = dataStr.split(' ')[0].match(/([1-9]\d*)/g);
        dateArr.unshift(year);
        return dateArr;
    }

    setCalendar() {
        const calendarDays = document.querySelector('#calendarDays');

        if (calendarDays.children.length <= 0) {
            builtCalendar(calendarDays);
        }

        const cYear = this.date.getFullYear();
        const cMonth = this.date.getMonth();
        const cDay = this.date.getDate();
        const cWeekday = new Date(cYear, cMonth, 1).getDay();
        const dayAmount = new Date(cYear, cMonth + 1, 0).getDate() + 1;

        const cyear = document.querySelectorAll('.cyear');
        const nyear = document.querySelectorAll('.nyear');

        let temp;
        let j = 0;
        for (let i = 0; i < cyear.length; i++) {
            cyear[i].parentElement.className = '';

            // 当一号周一时，新增一行，向下推七天显示出来
            // 当一号时周日时，一号会被吞掉，于是向下推七天显示出来
            if (i === 0 && (i - cWeekday === 0 || i - cWeekday === -1)) {
                j = 1;
            }

            temp = i - cWeekday + 2 - 7 * j;
            cyear[i].innerHTML = new Date(cYear, cMonth, temp).getDate();
            nyear[i].innerHTML = dateMap[new Date(cYear, cMonth, temp).toLocaleString('ja-JP-u-ca-chinese').match(/([1-9]\d*)/g)[1] - 1];
            if (temp === cDay) {
                cyear[i].parentElement.className = 'current-date';
            } else if (temp <= 0 || temp >= dayAmount) {
                cyear[i].parentElement.className = 'notCurrentMonth';
            }
        }
    }

    bindCtrl(pre, next) {
        const preId = pre.startsWith('#') ? pre : `#${pre}`;
        const nextId = next.startsWith('#') ? next : `#${next}`;

        // 日历部分按钮设置
        const preMonth = document.querySelector(preId);
        const nextMonth = document.querySelector(nextId);

        preMonth.addEventListener('click', () => {
            this.date.setMonth(this.date.getMonth() - 1);
            this.setCalendar();
            this.setMonth('#monthOnDatePanel');
        });

        nextMonth.addEventListener('click', () => {
            this.date.setMonth(this.date.getMonth() + 1);
            this.setCalendar();
            this.setMonth('#monthOnDatePanel');
        });
    }
}